package file;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.junit.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class UploadFileByForm {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
//		URL url = new URL("http://114.112.43.93/vvlive/uploadMoments");
		URL url = new URL("http://mp-up.51vv.com/upload_mpres");

		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		//httpURLConnection.setChunkedStreamingMode(128 * 1024);
		httpURLConnection.setDoInput(true);
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setUseCaches(false);
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
		httpURLConnection.setRequestProperty("Charset", "UTF-8");
		String boundary = "--WebKitFormBoundaryE19zNvXGzXaLvS5C";
		httpURLConnection.setRequestProperty("Content-Type",
				"multipart/form-data;boundary=" + boundary);

		String srcPath = "C:/Users/admin/Desktop/1.jpg";
		String twoHyphens = "--";
		String end = "\r\n";
		DataOutputStream dos = new DataOutputStream(httpURLConnection
				.getOutputStream());
		
		dos.writeBytes(end);
		dos.writeBytes(twoHyphens + boundary + end);
		dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end);
//		dos.writeBytes("Content-Type: image/jpeg" + end);
		dos.writeBytes(end);
		FileInputStream fis = new FileInputStream(new File(srcPath));
		byte[] buffer = new byte[8192]; // 8k
		int count = 0;
		while ((count = fis.read(buffer)) != -1) {
			dos.write(buffer, 0, count);
		}
		fis.close();
		dos.writeBytes(end);
//		dos.writeBytes(twoHyphens + boundary + end);
//		dos.writeBytes("Content-Disposition: form-data; name=\"transferType\"" + end);
//		dos.writeBytes(end);
//		dos.writeBytes("1" + end);
//		dos.writeBytes(twoHyphens + boundary + end);
//		dos.writeBytes("Content-Disposition: form-data; name=\"fmd5\"" + end);
//		dos.writeBytes(end);
//		dos.writeBytes("2636654af9ae189e3f0edaf176d16663" + end);
//		dos.writeBytes(twoHyphens + boundary + end);
//		dos.writeBytes("Content-Disposition: form-data; name=\"vvim\"" + end);
//		dos.writeBytes(end);
//		dos.writeBytes("5fa9c2a4d57c67221fc305eeaab4bade" + end);
		dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
		dos.flush();
		dos.close();

		if(httpURLConnection.getInputStream()!=null){
			BufferedReader br = new BufferedReader(new InputStreamReader(
					httpURLConnection.getInputStream(), "utf-8"));
			String line = null;
			System.out.println("#########################");
			while(br!=null && (line = br.readLine())!=null){
				System.out.println(line);
			}
			System.out.println("#########################");
			br.close();
		}
		
		if(httpURLConnection.getErrorStream()!=null){
			BufferedReader errorBr = new BufferedReader(new InputStreamReader(
					httpURLConnection.getErrorStream(), "utf-8"));
			String line = null;
			System.out.println("****************************");
			while(errorBr!=null && (line = errorBr.readLine())!=null){
				System.out.println(line);
			}
			System.out.println("****************************");
			errorBr.close();
		}
	}

	@Test
	public void updatePicTest() throws Exception {
		String serverUrl = "http://mp-up.51vv.com/upload_mpres";

		List<String[]> resultList = new ArrayList<>();

		File dir = new File("C:\\Users\\admin\\Desktop\\第二批专辑图片");

		File[] files = dir.listFiles();

		for(File f : files){
			String srcPath = f.getAbsolutePath().replace("\\","/");

			String result = uploadPic(serverUrl, srcPath);

			if(StringUtils.isNotBlank(result)){
				JSONObject jsonObject = JSONObject.fromObject(result);
				if(jsonObject.has("org_img_uri")){
					String orgValue = jsonObject.getString("org_img_uri");
					String bigValue = jsonObject.getString("big_img_uri");
					String smallValue = jsonObject.getString("small_img_uri");

					String fileNo = srcPath.substring(srcPath.lastIndexOf("/") + 1, srcPath.lastIndexOf("."));

					resultList.add(new String[]{fileNo,orgValue,bigValue,smallValue});

				}
			}
			Thread.sleep(10);
		}

		exportToExcel(resultList);

	}

	/**
	 * 上传图片接口返回的结果，告知客户端图片上传后的存储地址
	 * @param serverUrl 服务接口
	 * @param srcPath 图片绝对路径
	 * @return
	 * @throws Exception
     */
	private String uploadPic(String serverUrl,String srcPath) throws Exception{
		URL url = new URL(serverUrl);

		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		//httpURLConnection.setChunkedStreamingMode(128 * 1024);
		httpURLConnection.setDoInput(true);
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setUseCaches(false);
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
		httpURLConnection.setRequestProperty("Charset", "UTF-8");
		String boundary = "--WebKitFormBoundaryE19zNvXGzXaLvS5C";
		httpURLConnection.setRequestProperty("Content-Type",
				"multipart/form-data;boundary=" + boundary);

		String twoHyphens = "--";
		String end = "\r\n";
		DataOutputStream dos = new DataOutputStream(httpURLConnection
				.getOutputStream());

		dos.writeBytes(end);
		dos.writeBytes(twoHyphens + boundary + end);
		dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end);
		dos.writeBytes(end);
		FileInputStream fis = new FileInputStream(new File(srcPath));
		byte[] buffer = new byte[8192]; // 8k
		int count = 0;
		while ((count = fis.read(buffer)) != -1) {
			dos.write(buffer, 0, count);
		}
		fis.close();
		dos.writeBytes(end);
		dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
		dos.flush();
		dos.close();

		StringBuffer result = new StringBuffer();

		if(httpURLConnection.getInputStream()!=null){
			BufferedReader br = new BufferedReader(new InputStreamReader(
					httpURLConnection.getInputStream(), "utf-8"));
			String line = null;
			while(br!=null && (line = br.readLine())!=null){
				result.append(line);
			}
			br.close();
		}

		if(httpURLConnection.getErrorStream()!=null){
			BufferedReader errorBr = new BufferedReader(new InputStreamReader(
					httpURLConnection.getErrorStream(), "utf-8"));
			String line = null;
			System.out.println("****************************上传文件报错："+srcPath);
			while(errorBr!=null && (line = errorBr.readLine())!=null){
				System.out.println(line);
			}
			System.out.println("****************************");
			errorBr.close();
		}

		return result.toString();
	}

	/**
	 * 导出到excel
	 * @param list
     */
	private void exportToExcel(List<String[]> list){
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("专辑图片存储地址");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow(0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个靠左格式

		HSSFCell cell = row.createCell(0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("原始图片");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("大图片");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("小图片");
		cell.setCellStyle(style);

		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，

		for (int i = 0; i < list.size(); i++)
		{
			row = sheet.createRow(i + 1);
			String[] strings = list.get(i);
			// 第四步，创建单元格，并设置值
			for(int j=0;j<strings.length;j++){
				row.createCell(j).setCellValue(strings[j]);
			}
		}
		// 第六步，将文件存到指定位置
		try
		{
			FileOutputStream fout = new FileOutputStream("C:/Users/admin/Desktop/专辑图片存储地址.xls");
			wb.write(fout);
			fout.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}